package com.liu.design.behavior.chain.servlet;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LIU
 * @version 1.0
 * @description: filter链
 * @date 2022/12/20 15:17
 */

public class FilterChain implements Filter {
    // 游标
    int cursor = 0;
    // filter集合
    List<Filter> filterChains = new ArrayList<>();

    // 目标方法
    Target target;

    public void addFilter(Filter filter) {
        filterChains.add(filter);
    }

    public Target getTarget() {
        return target;
    }

    public void setTarget(Target target) {
        this.target = target;
    }


    @Override
    public void doFilter(Request request, Response response, FilterChain chain) {

        if (cursor != filterChains.size()) {

            Filter filter = filterChains.get(cursor);
            //游标
            cursor++;
            //执行filter方法
            filter.doFilter(request, response, chain);
        } else {
            //执行目标方法
            target.hello();
        }

    }
}
